import type { IScheduleState } from './scheduleStore';
import { scheduleService } from '@/services/schedule';
import type { 
  IScheduleTemplateCreateRequest, 
  IScheduleTemplateUpdateRequest,
  IScheduleTemplateQueryParams
} from '@/types/schedule/scheduleTemplate';
import type { 
  IScheduleInstanceCreateRequest, 
  IScheduleInstanceUpdateRequest,
  IScheduleInstanceQueryParams
} from '@/types/schedule/scheduleInstance';
import { ScheduleViewTypeEnum } from '@/types/schedule/enums';

/**
 * 课表状态管理Actions实现
 * @description 将Actions实现分离到单独文件中以提高可维护性
 */
export const createScheduleActions = (set: any, get: () => IScheduleState) => ({
  // 模板数据操作
  updateTemplate: async (id: string, templateData: Omit<IScheduleTemplateUpdateRequest, 'id'>) => {
    set((state: IScheduleState) => {
      state.templateAsync.loading = true;
      state.templateAsync.error = null;
    });

    try {
      const result = await scheduleService.updateTemplate(id, templateData);
      if (result.success) {
        set((state: IScheduleState) => {
          const index = state.templates.findIndex(template => template.id === id);
          if (index !== -1) {
            state.templates[index] = result.data;
          }
          if (state.selectedTemplate?.id === id) {
            state.selectedTemplate = result.data;
          }
          state.templateAsync.loading = false;
          state.showTemplateForm = false;
        });
      } else {
        set((state: IScheduleState) => {
          state.templateAsync.loading = false;
          state.templateAsync.error = result.error;
        });
        throw new Error(result.error);
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.templateAsync.loading = false;
        state.templateAsync.error = error instanceof Error ? error.message : '更新课程模板失败';
      });
      throw error;
    }
  },

  deleteTemplate: async (id: string) => {
    try {
      const result = await scheduleService.deleteTemplate(id);
      if (result.success) {
        set((state: IScheduleState) => {
          state.templates = state.templates.filter(template => template.id !== id);
          if (state.selectedTemplate?.id === id) {
            state.selectedTemplate = null;
          }
          state.selectedTemplateIds = state.selectedTemplateIds.filter(selectedId => selectedId !== id);
        });
      } else {
        set((state: IScheduleState) => {
          state.templateAsync.error = result.error;
        });
        throw new Error(result.error);
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.templateAsync.error = error instanceof Error ? error.message : '删除课程模板失败';
      });
      throw error;
    }
  },

  generateInstances: async (templateId: string) => {
    set((state: IScheduleState) => {
      state.instanceAsync.loading = true;
      state.instanceAsync.error = null;
    });

    try {
      const result = await scheduleService.generateInstances(templateId);
      if (result.success) {
        set((state: IScheduleState) => {
          // 添加新生成的实例到列表中
          state.instances.push(...result.data);
          state.instanceAsync.loading = false;
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.loading = false;
          state.instanceAsync.error = result.error;
        });
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.loading = false;
        state.instanceAsync.error = error instanceof Error ? error.message : '生成课程实例失败';
      });
    }
  },

  // 实例数据操作
  fetchInstances: async (queryParams?: IScheduleInstanceQueryParams) => {
    set((state: IScheduleState) => {
      state.instanceAsync.loading = true;
      state.instanceAsync.error = null;
    });

    try {
      const result = await scheduleService.getAllInstances(queryParams);
      if (result.success) {
        set((state: IScheduleState) => {
          state.instances = result.data;
          state.instanceAsync.loading = false;
          state.instanceAsync.lastUpdated = Date.now();
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.loading = false;
          state.instanceAsync.error = result.error;
        });
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.loading = false;
        state.instanceAsync.error = error instanceof Error ? error.message : '获取课程实例失败';
      });
    }
  },

  fetchInstancesByDate: async (date: string, studentIds?: string[]) => {
    set((state: IScheduleState) => {
      state.instanceAsync.loading = true;
      state.instanceAsync.error = null;
    });

    try {
      const result = await scheduleService.getInstancesByDate(date, studentIds);
      if (result.success) {
        set((state: IScheduleState) => {
          state.instances = result.data;
          state.instanceAsync.loading = false;
          state.instanceAsync.lastUpdated = Date.now();
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.loading = false;
          state.instanceAsync.error = result.error;
        });
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.loading = false;
        state.instanceAsync.error = error instanceof Error ? error.message : '获取日期课程实例失败';
      });
    }
  },

  fetchInstancesByDateRange: async (dateFrom: string, dateTo: string, studentIds?: string[]) => {
    set((state: IScheduleState) => {
      state.instanceAsync.loading = true;
      state.instanceAsync.error = null;
    });

    try {
      const result = await scheduleService.getInstancesByDateRange(dateFrom, dateTo, studentIds);
      if (result.success) {
        set((state: IScheduleState) => {
          state.instances = result.data;
          state.instanceAsync.loading = false;
          state.instanceAsync.lastUpdated = Date.now();
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.loading = false;
          state.instanceAsync.error = result.error;
        });
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.loading = false;
        state.instanceAsync.error = error instanceof Error ? error.message : '获取日期范围课程实例失败';
      });
    }
  },

  completeInstance: async (id: string) => {
    try {
      const result = await scheduleService.completeInstance(id);
      if (result.success) {
        set((state: IScheduleState) => {
          const index = state.instances.findIndex(instance => instance.id === id);
          if (index !== -1) {
            state.instances[index] = result.data;
          }
          if (state.selectedInstance?.id === id) {
            state.selectedInstance = result.data;
          }
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.error = result.error;
        });
        throw new Error(result.error);
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.error = error instanceof Error ? error.message : '完成课程实例失败';
      });
      throw error;
    }
  },

  cancelInstance: async (id: string, reason?: string) => {
    try {
      const result = await scheduleService.cancelInstance(id, reason);
      if (result.success) {
        set((state: IScheduleState) => {
          const index = state.instances.findIndex(instance => instance.id === id);
          if (index !== -1) {
            state.instances[index] = result.data;
          }
          if (state.selectedInstance?.id === id) {
            state.selectedInstance = result.data;
          }
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.error = result.error;
        });
        throw new Error(result.error);
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.error = error instanceof Error ? error.message : '取消课程实例失败';
      });
      throw error;
    }
  },

  addMakeupInstance: async (templateId: string, date: string, startTime?: string, endTime?: string) => {
    set((state: IScheduleState) => {
      state.instanceAsync.loading = true;
      state.instanceAsync.error = null;
    });

    try {
      const result = await scheduleService.addMakeupInstance(templateId, date, startTime, endTime);
      if (result.success) {
        set((state: IScheduleState) => {
          state.instances.push(result.data);
          state.instanceAsync.loading = false;
        });
      } else {
        set((state: IScheduleState) => {
          state.instanceAsync.loading = false;
          state.instanceAsync.error = result.error;
        });
        throw new Error(result.error);
      }
    } catch (error) {
      set((state: IScheduleState) => {
        state.instanceAsync.loading = false;
        state.instanceAsync.error = error instanceof Error ? error.message : '添加补课实例失败';
      });
      throw error;
    }
  },

  // 冲突检测
  checkTemplateConflict: async (templateData: IScheduleTemplateCreateRequest) => {
    set((state: IScheduleState) => {
      state.conflictAsync.loading = true;
      state.conflictAsync.error = null;
    });

    try {
      // 这里需要调用冲突检测服务
      // const result = await scheduleService.checkTemplateConflict(templateData);
      // 暂时模拟实现
      set((state: IScheduleState) => {
        state.conflicts = [];
        state.conflictAsync.loading = false;
        state.conflictAsync.lastUpdated = Date.now();
      });
    } catch (error) {
      set((state: IScheduleState) => {
        state.conflictAsync.loading = false;
        state.conflictAsync.error = error instanceof Error ? error.message : '检查模板冲突失败';
      });
    }
  },

  checkInstanceConflict: async (instanceData: IScheduleInstanceCreateRequest) => {
    set((state: IScheduleState) => {
      state.conflictAsync.loading = true;
      state.conflictAsync.error = null;
    });

    try {
      // 这里需要调用冲突检测服务
      // const result = await scheduleService.checkInstanceConflict(instanceData);
      // 暂时模拟实现
      set((state: IScheduleState) => {
        state.conflicts = [];
        state.conflictAsync.loading = false;
        state.conflictAsync.lastUpdated = Date.now();
      });
    } catch (error) {
      set((state: IScheduleState) => {
        state.conflictAsync.loading = false;
        state.conflictAsync.error = error instanceof Error ? error.message : '检查实例冲突失败';
      });
    }
  },

  clearConflicts: () => {
    set((state: IScheduleState) => {
      state.conflicts = [];
      state.conflictAsync.error = null;
    });
  }
});